from flask import Blueprint, request

from utilsapp.mysql_con import db_connect
from utilsapp.mysql_con import db_operation
from utilsapp.common import parsing_permissions

order = Blueprint('order', __name__)


@order.route('/getlist', methods=["post"])
def get_notify_list():
    flag = parsing_permissions(request)  # 获取用户权限
    warnpermission = flag['warnpermission']
    size = int(request.json.get('size'))
    page = int(request.json.get('page'))
    scope_id = 0 if not request.json.get(
        'scope_id') else request.json.get('scope_id')
    user_id = 0 if not request.json.get(
        'user_id') else request.json.get('user_id')
    warn_level = 0 if not request.json.get(
        'warn_level') else request.json.get('warn_level')
    device_name = 0 if not request.json.get(
        "device_name") else request.json.get("device_name")
    start_time = 0 if not request.json.get(
        "start_time") else request.json.get("start_time")
    end_time = 0 if not request.json.get(
        "end_time") else request.json.get("end_time")
    warn_source = 0 if not request.json.get(
        "warn_source") else request.json.get("warn_source")
    is_handled = "" if not request.json.get(
        "is_handled") else request.json.get("is_handled")
    if warnpermission == 0:  # 非管理员，只能看自己能处理的工单
        sql = f"""SELECT n.id, n.title,n.device_id,d.device_name,n.content,n.warn_source,n.warn_level,n.warn_time,
        n.is_handled,n.create_time,n.user_id,u.nick_name,n.accept_id,u2.nick_name as accept_name,n.handle_content FROM 
        notify n,device d,userinfo u,userinfo u2 WHERE n.accept_id ={user_id} and d.id=n.device_id and u.id = n.user_id
        and  u2.id = n.accept_id and 
        IF({warn_level}=0 ,""="",n.warn_level={warn_level}) and
        IF('{device_name}'='0' ,""="",d.device_name like '%{device_name}%')  and 
        IF('{start_time}'= '0' ,""="",n.create_time > '{start_time}') and 
        IF('{end_time}'='0' ,""="",n.create_time < '{end_time}') and 
        IF('{warn_source}'='0' ,""="",n.warn_source ={warn_source}) and
        IF('{is_handled}'='' ,""="",n.is_handled  ='{is_handled}') ORDER BY create_time desc
        LIMIT {max(0, (page - 1) * size)},{size}"""
     
        sql_1 = f"""SELECT count(*) as num FROM notify n,device d,userinfo u WHERE
        n.accept_id ={user_id} and d.id=n.device_id and u.id = n.user_id and 
        IF({warn_level}=0 ,""="",n.warn_level={warn_level}) and
        IF('{device_name}'='0' ,""="",d.device_name like '%{device_name}%')  and 
        IF('{start_time}'= '0' ,""="",n.create_time > '{start_time}') and 
        IF('{end_time}'='0' ,""="",n.create_time < '{end_time}') and 
        IF('{warn_source}'='0' ,""="",n.warn_source ={warn_source}) and
        IF('{is_handled}'='' ,""="",n.is_handled  ='{is_handled}') """
        sql_2 = f"""SELECT is_handled,COUNT(is_handled) as num FROM notify n,device d,userinfo u WHERE
        n.accept_id ={user_id} and d.id=n.device_id and u.id = n.user_id and 
        IF({warn_level}=0 ,""="",n.warn_level={warn_level}) and
        IF('{device_name}'='0' ,""="",d.device_name like '%{device_name}%')  and 
        IF('{start_time}'= '0' ,""="",n.create_time > '{start_time}') and 
        IF('{end_time}'='0' ,""="",n.create_time < '{end_time}') and 
        IF('{is_handled}'='' ,""="",n.is_handled  ='{is_handled}') and
        IF('{warn_source}'='0' ,""="",n.warn_source ={warn_source}) GROUP BY is_handled
        """
    else:  # 管理员，可以看所属区域的工单
        if scope_id != 0:  # 带scope,则查询相关区域的ID
            scope_sql = f"""SELECT type FROM regionlevel where id = {scope_id} """
            type_ = db_connect(scope_sql)["data"][0]["type"]
            whe = f"""n.{type_}_id={scope_id} and"""
        else:
            data_id = flag['dataId']
            if data_id == 0:
                whe = ""
            else:
                type_sql = f"""SELECT type FROM regionlevel where id = {data_id} """
                type_ = db_connect(type_sql)["data"][0]["type"]
                whe = f"""n.{type_}_id={data_id} and"""
        sql = f"""SELECT n.id, n.title,n.device_id,d.device_name,n.content,n.warn_source,n.warn_level,n.warn_time,
        n.is_handled,n.create_time,n.user_id,u.nick_name,n.accept_id,u2.nick_name as accept_name,n.handle_content FROM 
        notify n,device d,userinfo u,userinfo u2 WHERE {whe}
        d.id=n.device_id and u.id = n.user_id and  u2.id = n.accept_id and 
        IF({warn_level}=0 ,""="",n.warn_level={warn_level}) and
        IF('{device_name}'='0' ,""="",d.device_name like '%{device_name}%')  and 
        IF('{start_time}'= '0' ,""="",n.create_time > '{start_time}') and 
        IF('{end_time}'='0' ,""="",n.create_time < '{end_time}') and 
        IF('{warn_source}'='0' ,""="",n.warn_source ={warn_source}) and 
        IF('{is_handled}'='' ,""="",n.is_handled  ='{is_handled}')  ORDER BY create_time desc
        LIMIT {max(0, (page - 1) * size)},{size}"""

        sql_1 = f"""SELECT count(*) as num FROM notify n,device d,userinfo u WHERE {whe}
        d.id=n.device_id and u.id = n.user_id and 
        IF({warn_level}=0 ,""="",n.warn_level={warn_level}) and 
        IF('{device_name}'='0' ,""="",d.device_name like '%{device_name}%') and 
        IF('{start_time}'= '0' ,""="",n.create_time > '{start_time}') and 
        IF('{end_time}'='0' ,""="",n.create_time < '{end_time}') and 
        IF('{is_handled}'='' ,""="",n.is_handled  ='{is_handled}') and 
        IF('{warn_source}'='0' ,""="",n.warn_source ={warn_source})"""
        sql_2 = f"""SELECT is_handled,COUNT(is_handled) as num FROM notify n,device d,userinfo u WHERE {whe}
        d.id=n.device_id and u.id = n.user_id and 
        IF({warn_level}=0 ,""="",n.warn_level={warn_level}) and
        IF('{device_name}'='0' ,""="",d.device_name like '%{device_name}%')  and 
        IF('{start_time}'= '0' ,""="",n.create_time > '{start_time}') and 
        IF('{end_time}'='0' ,""="",n.create_time < '{end_time}') and 
        IF('{is_handled}'='' ,""="",n.is_handled  ='{is_handled}') and
        IF('{warn_source}'='0' ,""="",n.warn_source ={warn_source}) GROUP BY is_handled
        """
    total_num = db_connect(sql_1)
    total = total_num['data'][0]['num']
    res = db_connect(sql)
    order_num = db_connect(sql_2)
    if order_num["data"]:
        stat = dict()
        stat["total"] = total
        stat["handled"] = 0
        stat["unHandled"] = 0
        for i in order_num["data"]:

            if i["is_handled"] == "1":
                stat["handled"] = i['num']
            elif i["is_handled"] == '0':
                stat["unHandled"] = i['num']
            else:
                pass
    else:
        stat = dict()
        stat["total"] = total
        stat["handled"] = 0
        stat["unHandled"] = 0
    if res['code'] == 0:
        return {
            'msg': '查询成功',
            'code': 0,
            'data': res['data'],
            'pagination': {
                "page": page,
                "pageSize": size,
                "total": total,
                "stat": stat
            }
        }
    else:
        return res


# 删除工单
@order.route('/delete')
def order_delete():
    # 删除工单的同时将对应告警的 notice 字段 设为 0
    id_ = int(request.args.get('id'))

    sql = f" delete from notify where id = {id_}"

    res = db_operation(sql)

    affected_rows = res['Affected_rows']
    if affected_rows >= 1:
        return {
            'code': 0,
            'msg': '删除成功',
            'data': res
        }
    else:
        return {
            'code': -1,
            'msg': '删除失败'
        }


# 更改工单
@order.route('/change', methods=["post"])
def order_change():

    id = request.json.get('id')
    warn_id = request.json.get('warn_id')
    handle_content = request.json.get('handle_content')

    sql = f"""UPDATE notify set is_handled = '1', handle_content ='{handle_content}' WHERE id = {id} """
    # 处理工单的同时将对应告警的notice 字段 改为 2
    sql_1 = f"""update notify set notice =2 where  id = {warn_id}"""
    db_operation(sql_1)

    res = db_operation(sql)
    affected_rows = res['Affected_rows']
    sql1 = f"""UPDATE warn set is_handled = 1 WHERE id= {warn_id} """

    res1 = db_operation(sql1)

    affected_rows1 = res1['Affected_rows']
    if affected_rows >= 1:
        return {
            'code': 0,
            'msg': '更改成功',
            'data': res
        }
    else:
        return {
            'code': 1,
            'msg': '更改失败'
        }
